import sys
import os
from kconfiglib import Kconfig

# Adapted from edk2-nvidia/Silicon/NVIDIA/edk2nv/stuart/builder.py BuildConfigFile method
def build_config_file(kconf_path, defconfig_file, config_out):
    kconf = Kconfig(kconf_path, warn_to_stderr=False,
                    suppress_traceback=True)
    kconf.warn_assign_undef = True
    kconf.warn_assign_override = False
    kconf.warn_assign_redun = False

    configs = [defconfig_file]
    print(kconf.load_config(configs[0]))
    for config in configs[1:]:
        # replace=False creates a merged configuration
        print(kconf.load_config(config, replace=False))

    if os.path.exists(config_out):
        print(kconf.load_config(config_out, replace=False))

    kconf.write_config(os.devnull)

    if kconf.warnings:
        # Put a blank line between warnings to make them easier to read
        for warning in kconf.warnings:
            print("\n" + warning, file=sys.stderr)

        # Turn all warnings into errors, so that e.g. assignments to undefined
        # Kconfig symbols become errors.
        #
        # A warning is generated by this script whenever a symbol gets a
        # different value than the one it was assigned. Keep that one as just a
        # warning for now.
        raise ValueError("Aborting due to Kconfig warnings")

    # Write the merged configuration
    print(kconf.write_config(config_out))
    return 0

build_config_file(sys.argv[1], sys.argv[2], sys.argv[3])

with open(sys.argv[3], "r") as f, open(sys.argv[4], "w") as fo:
    for line in f:
        fo.write(line.replace('"', '').replace("'", ""))
